package com.hmall.order.service.impl;

import cn.itcast.pojo.ItemDoc;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.dto.AddressDTO;
import com.hmall.common.dto.Item;
import com.hmall.common.dto.ItemClient;
import com.hmall.common.dto.feign.UserClient;
import com.hmall.order.mapper.OrderMapper;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.pojo.OrderLogistics;
import com.hmall.order.pojo.RequestParams;
import com.hmall.order.service.IOrderDetailService;
import com.hmall.order.service.IOrderLogisticsService;
import com.hmall.order.service.IOrderService;
import com.hmall.order.utils.ThreadUserId;
import lombok.extern.slf4j.Slf4j;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.nio.charset.StandardCharsets;
import java.util.UUID;
@Transactional
@Slf4j
@Service
public class OrderService extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    @Autowired
    private ItemClient itemClient;
    @Autowired
    private IOrderDetailService  orderDetailService;
    @Autowired
    private  IOrderLogisticsService  orderLogisticsService;
    @Autowired
    private UserClient userClient;

    @Autowired
    private RabbitTemplate rabbitTemplate;
    //创建订单
    @Override
    public Long order(RequestParams params) {
       //查询商品
        Item item = itemClient.getByid(params.getItemId());
        //基于商品价格以及购买计算商品总价
        long totalFee = item.getPrice() * params.getNum();
        //设置订单总价
        Order order = new Order();
        order.setTotalFee(totalFee);
        order.setPaymentType(params.getPaymentType());
        order.setUserId(ThreadUserId.getUserId());
        order.setStatus(1);
        //更新数据库
        this.save(order);
        //封装订单信息对象
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setName(item.getName());
        orderDetail.setSpec(item.getSpec());
        orderDetail.setPrice(item.getPrice());
        orderDetail.setNum(params.getNum());
        orderDetail.setItemId(item.getId());
        orderDetail.setImage(item.getImage());
        orderDetail.setOrderId(order.getId());
           orderDetailService.save(orderDetail);
           //获取收件地址信息
        Long addressId = params.getAddressId();
        AddressDTO address = userClient.findAddressById(addressId);

        //降低至封装成OrderLogistics对象，写入tb_order_logistics表
        OrderLogistics orderLogistics = new OrderLogistics();
        BeanUtils.copyProperties(address,orderLogistics);
         orderLogistics.setOrderId(order.getId());
         orderLogisticsService.save(orderLogistics);

         //扣减库存
        try {
            itemClient.updateStock(params.getItemId(),params.getNum());
        } catch (Exception e) {
            throw new RuntimeException("库存不足");
        }

        //处理超时信息
        Message message = MessageBuilder
                .withBody("hello, ttl message".getBytes(StandardCharsets.UTF_8))
                .setExpiration("3000") //延迟60秒
                .build();

             //消息id，封装得到CorrelationData中
        CorrelationData correlationData = new CorrelationData(order.getId().toString());
        //发送消息
        rabbitTemplate.convertAndSend("order.topic","order.create",message,correlationData);
         //打印成功日志
          log.info("发送消息成功");
        return order.getId();
    }
}
